package com.sms.model;

import com.sms.exception.DataFileCorruptedException;
import com.sms.util.FileUtil;
import com.sms.util.ValidateUtil;

import java.io.IOException;
import java.util.List;

import static com.sms.constants.SystemConstants.SCORE_FILE;

/**
 * 成绩实体类
 * 位置：com.sms.model.Score
 */
public class Score {
    // 属性定义
    private String studentId;  // 学生ID，外键
    private String courseId;   // 课程ID，外键  
    private double score;      // 成绩，0-100
    private String examDate;     // 考试日期

    public String getStudentId() {
        return studentId;
    }

    public void setStudentId(String studentId) {
        this.studentId = studentId;
    }

    public String getCourseId() {
        return courseId;
    }

    public void setCourseId(String courseId) {
        this.courseId = courseId;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    public String getExamDate() {
        return examDate;
    }

    public void setExamDate(String examDate) {
        this.examDate = examDate;
    }


    /**
     * 验证成绩数据有效性
     *
     * @return true-数据有效, false-数据无效
     */
    public boolean isValid() {
        return ValidateUtil.isValidScore(this.getScore());
    }

    /**
     * 转换为文件存储格式
     * @return CSV格式字符串："studentId,courseId,score,examDate"
     */
    public String toFileString(){
        return this.studentId + ","
                + this.courseId + ","
                + this.score + ","
                + this.examDate
                + System.lineSeparator();
    }

    /**
     * 从文件行解析成绩对象
     * @param line 文件行内容（CSV格式）
     * @return 解析后的Score对象
     * @throws IOException                当文件读取失败时抛出
     * @throws DataFileCorruptedException 当数据格式错误时抛出
     */
    public static Score fromFileString(String line) throws DataFileCorruptedException, IOException {
        List<Score> scores = FileUtil.loadScores(SCORE_FILE);

        return scores.get(Integer.parseInt(line));
    }
}